package worklog.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import worklog.db.EntryDB;
import worklog.dto.DayDTO;
import worklog.dto.ResponseDTO;

import worklog.DaysCalculator;

@WebServlet("/week")
public class Week extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private EntryDB entryDB;
	private ResponseDTO responder = new ResponseDTO();
	
    public Week() throws Exception{ super(); }
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
		//doGet(request, response); 
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
		entryDB = new EntryDB();
		PrintWriter out = response.getWriter();
		response.setContentType("application/json");
    	if (entryDB.isReady()) out.print(processRequest(request));
    	else out.print(responder.showError("DB connection error"));
    	entryDB.close();
    	out.close();
	}
	
	private String processRequest(HttpServletRequest request){
		HttpSession session = request.getSession();
		if (session.getAttribute("logged") == null || (Boolean)session.getAttribute("logged") != true) return responder.showAuthError();
		int userId = (Integer) session.getAttribute("userId");

		String dateStr = request.getParameter("date");
    	String showWeekendsStr = request.getParameter("showWeekends");
    	Boolean showWeekends = (showWeekendsStr.equals("true"));
    	
    	if (dateStr == null || dateStr.isEmpty()) return responder.showError("Incorrect parameters");

    	ArrayList<String> week = new ArrayList<String>();
    	DayDTO day = new DayDTO();
    	String[] weekDays = DaysCalculator.getWeekDates(dateStr, showWeekends);
    	
    	for (String dat : weekDays){
    		try { day = entryDB.getDay(userId, dat); } catch (SQLException e) {}
    		if (day != null) week.add(day.toString());
    	}
		
		if (week.size()>0) return week.toString();
		return responder.showError("No entries found");
	}
}